<template>
  <q-dialog v-model="visible" :persistent="invalid">
    <q-card style="min-width: 300px" class="overflow-hidden">
      <get-current-posture ref="getCurrent" v-model="posture" />
      <q-card-section class="flex items-center q-gutter-x-sm">
        <div class="text-h6">
          {{ props.modify ? posture.name + $t(lang + "姿态修改") : $t("add") }}
          <span v-if="!modify">{{ postureTypes[posture.type] }}</span>
        </div>
        <q-space />
        <q-btn
          v-if="modify"
          color="negative"
          @click="postureDelete"
          :label="$t('del')"
          icon="delete"
        />
        <q-btn
          no-caps
          color="primary"
          @click="moveToPosture(posture.id)"
          icon="precision_manufacturing"
          v-if="
            isConnected && modify && posture.id && posture.type !== 'reference'
          "
          :label="$t(lang + '移动')"
        />
        <q-btn
          no-caps
          color="primary"
          @click="moveToPosture(posture.id)"
          icon="precision_manufacturing"
          v-if="
            isConnected &&
            modify &&
            posture.id &&
            posture.type === 'reference' &&
            useFunctionsStore().mode === 'remote'
          "
          :label="$t(lang + '移动')"
        />
        <q-btn
          no-caps
          v-if="!modify"
          color="negative"
          @click="giveUpCreate"
          :label="$t(lang + '放弃新增')"
          icon="delete"
          v-close-popup
        />
      </q-card-section>
      <q-separator />
      <q-card-section class="q-gutter-y-sm">
        <div class="row q-gutter-x-sm">
          <q-select
            dense
            style="min-width: 14rem"
            outlined
            behavior="menu"
            clearable
            :label="$t(lang + '参考坐标')"
            emit-value
            map-options
            v-model="targetFrame"
            :options="frameOptions"
          />
          <q-select
            dense
            style="min-width: 14rem"
            outlined
            behavior="menu"
            clearable
            :label="$t(lang + '工具坐标')"
            emit-value
            map-options
            v-model="sourceFrame"
            :options="frameOptions"
          />
          <q-btn
            no-caps
            :label="$t(lang + '获取')"
            color="primary"
            @click="getPosture"
            v-if="targetFrame && sourceFrame"
          />
        </div>
        <q-separator />
        <q-item-label class="text-subtitle1 text-grey-8">{{
          $t(lang + "姿态信息")
        }}</q-item-label>
        <div class="row q-gutter-x-sm">
          <q-input
            readonly
            dense
            outlined
            v-model="posture.id"
            class="col"
            label="id"
          />
          <q-input
            readonly
            dense
            outlined
            v-model="posture.frameID"
            class="col"
            :label="$t(lang + '参考坐标')"
          />
          <q-input
            readonly
            dense
            outlined
            v-model="posture.toolFrameId"
            class="col"
            :label="$t(lang + '工具坐标')"
          />
          <q-input
            dense
            outlined
            v-model="posture.name"
            class="col"
            :label="$t(lang + '名称')"
          />
        </div>
        <q-separator />
        <q-item-label class="text-subtitle1 text-grey-8">{{
          $t(lang + "位置信息")
        }}</q-item-label>
        <div class="row q-gutter-x-sm">
          <q-input
            dense
            outlined
            type="tel"
            v-model.number="posture.x"
            class="col"
            label="X"
          />
          <q-input
            dense
            outlined
            type="tel"
            v-model.number="posture.y"
            class="col"
            label="Y"
          />
          <q-input
            dense
            outlined
            type="tel"
            v-model.number="posture.z"
            class="col"
            label="Z"
          />
        </div>
        <q-separator />
        <q-item-label class="text-subtitle1 text-grey-7">{{
          $t(lang + "角度信息")
        }}</q-item-label>
        <div class="row q-gutter-x-sm">
          <q-input
            dense
            outlined
            type="tel"
            v-model.number="posture.qx"
            class="col"
            label="X"
          />
          <q-input
            dense
            outlined
            type="tel"
            v-model.number="posture.qy"
            class="col"
            label="Y"
          />
          <q-input
            dense
            outlined
            type="tel"
            v-model.number="posture.qz"
            class="col"
            label="Z"
          />
          <q-input
            dense
            outlined
            type="tel"
            v-model.number="posture.qw"
            class="col"
            label="W"
          />
        </div>
      </q-card-section>
      <q-slide-transition>
        <div v-if="!invalid">
          <q-btn
            no-caps
            class="full-width"
            stretch
            :label="modify ? $t(lang + '确认修改') : $t(lang + '确认新增')"
            icon="check"
            color="primary"
            v-close-popup
          />
        </div>
      </q-slide-transition>
      <q-inner-loading
        :showing="loading"
        :label="$t(lang + '获取姿态数据中')"
        label-class="text-teal"
        label-style="font-size: 1.1em"
      />
    </q-card>
  </q-dialog>
</template>

<script setup>
import { computed, ref } from "vue";
import { useQuasar } from "quasar";
import { api } from "boot/axios.js";
import { useAPIStore } from "stores/api";
import { isConnected } from "src/utils/deviceWs";
import GetCurrentPosture from "components/posture/GetCurrentPosture.vue";
import { useFunctionsStore } from "stores/functions";
import { useUiStore } from "stores/ui";
import { useI18n } from "vue-i18n";

const t = useI18n().t;
const lang = "StorageManage.ModifyStoragePosture.";
const postureTypes = {
  reference: t(lang + "参考姿态"),
  home: t(lang + "准备姿态"),
  calibration: t(lang + "校准姿态"),
  transition: t(lang + "过渡姿态"),
};
defineExpose({ show });
const props = defineProps({
  modify: { type: Boolean, default: false },
});
const emit = defineEmits(["remove"]);
const $q = useQuasar();
const ui = useUiStore();
const visible = ref(false);
const loading = ref(false);
const posture = ref({}); // 姿态数据
const invalid = computed(
  () =>
    !posture.value.name ||
    !(
      posture.value.x ||
      posture.value.y ||
      posture.value.z ||
      posture.value.qx ||
      posture.value.qy ||
      posture.value.qz ||
      posture.value.qw
    )
); // 判断是否修改
const getCurrent = ref();
const targetFrame = ref(""); // 参考坐标
const sourceFrame = ref(""); // 工具坐标
const frameOptions = ref([]); // 坐标系选项
const modify = computed(() => props.modify);
function show(data, norm, index) {
  getFrameList();
  posture.value = data;
  visible.value = true;
  posture.value.scenario = useFunctionsStore().scene.id;
  switch (posture.value.type) {
    case "home":
      targetFrame.value = "arm_base";
      sourceFrame.value = "flange";
      if (!modify.value) {
        getPosture();
        posture.value.name = "home" + index;
      }
      break;
    case "calibration":
      targetFrame.value = "arm_base";
      sourceFrame.value = "flange";
      if (!modify.value) {
        getCord();
        posture.value.name = "photo";
      }
      break;
    case "transition":
      console.log("111");
      if (norm.onRobot) {
        targetFrame.value = "arm_base";
        sourceFrame.value = "flange";
      } else {
        targetFrame.value = "platform";
        sourceFrame.value = "flange";
      }
      if (!modify.value) {
        getPosture();
        posture.value.name = "middle_" + (Number(index) + 1);
      }
      break;
    case "reference":
      if (norm.onRobot) {
        targetFrame.value = "arm_base";
        sourceFrame.value = "flange";
      } else {
        targetFrame.value = "platform";
        sourceFrame.value = "flange";
      }
      if (!modify.value) {
        getPosture();
      }
      break;
  }
}

// 拍照点获取坐标
function getCord() {
  loading.value = true;
  api
    .post(
      useAPIStore().amrUrl + "ros/call",
      {},
      { params: { service: "/recognize" } }
    )
    .then((res) => {
      if (res.data.values.flag === 1) {
        getPosture();
      } else {
        loading.value = false;
        $q.dialog({
          dark: ui.isDark,
          title: t(lang + "校准点获取失败"),
          message: t(lang + "是否重新获取校准点"),
          cancel: t(lang + "退出"),
          ok: t(lang + "重试"),
        })
          .onOk(() => {
            getCord();
          })
          .onCancel(() => {
            visible.value = false;
            giveUpCreate();
          });
      }
    })
    .catch(() => {
      loading.value = false;
    });
}
// 获取所有坐标系
function getFrameList() {
  api
    .post(
      useAPIStore().amrUrl + "ros/call",
      {},
      { params: { service: "tf/list_frames" } }
    )
    .then((res) => {
      frameOptions.value = res.data.values.frames;
    });
}

// 获取坐标系下面的点位信息
function getPosture() {
  loading.value = true;
  api
    .post(
      useAPIStore().amrUrl + "ros/call",
      {
        target_frame: targetFrame.value,
        source_frame: sourceFrame.value,
      },
      { params: { service: "tf/get_frame_pose" } }
    )
    .then((res) => {
      setTimeout(() => {
        loading.value = false;
      }, 700);
      const pose = res.data.values.pose;
      posture.value.frameID = pose.header.frame_id;
      posture.value.toolFrameId = sourceFrame.value;
      posture.value.qw = pose.pose.orientation.w;
      posture.value.qx = pose.pose.orientation.x;
      posture.value.qy = pose.pose.orientation.y;
      posture.value.qz = pose.pose.orientation.z;
      posture.value.x = pose.pose.position.x;
      posture.value.y = pose.pose.position.y;
      posture.value.z = pose.pose.position.z;
    })
    .then(() => {
      $q.notify({
        type: "positive",
        message: t(lang + "获取姿态成功"),
      });
    })
    .catch(() => {
      loading.value = false;
      $q.notify({
        type: "negative",
        message: t(lang + "获取姿态失败"),
      });
      $q.dialog({
        dark: ui.isDark,
        title: t(lang + "获取姿态失败请检查机械臂是否正常"),
        ok: t("know"),
        cancel: false,
      }).onOk(() => {
        visible.value = false;
        giveUpCreate();
      });
    });
}
// 当前姿态移动
function moveToPosture(id) {
  $q.dialog({
    title: "移动",
    message: "请选择移动类型",
    options: {
      type: "radio",
      model: "joint",
      // inline: true
      items: [
        { label: "关节", value: "joint" },
        { label: "直线", value: "linear" },
      ],
    },
    cancel: t("cancel"),
    ok: t("ok"),
    persistent: true,
  }).onOk((data) => {
    api
      .get(useAPIStore().amrUrl + "amr/add", {
        params: { type: "posture", content: id + "," + data },
      })
      .then((rs) => {
        if (rs.data === "done") {
          $q.notify({
            type: "positive",
            message: t(lang + "指令已下发"),
            position: "bottom",
          });
        }
      })
      .catch(() => {
        $q.notify({
          type: "negative",
          message: t(lang + "接口调用出现错误"),
          position: "bottom",
        });
      });
  });
}
// 姿态删除
function postureDelete() {
  $q.dialog({
    dark: ui.isDark,
    title: t("del") + posture.value.name + t(lang + "姿态"),
    message: t(lang + "是否要删除该姿态"),
    cancel: t("cancel"),
    ok: t("ok"),
  }).onOk(() => {
    emit("remove", posture.value);
    visible.value = false;
  });
}
// 放弃新增
function giveUpCreate() {
  emit("remove", posture.value);
  visible.value = false;
}
</script>
